package com.paas.user.interceptor;

import com.paas.model.LoginUser;
import com.paas.util.CommonUtil;
import com.paas.util.JWTUtil;
import com.paas.util.JsonData;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author pangjs
 * @version 0.1
 * @date 2021/7/30 11:05 上午
 * @description 登录拦截器
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    //保存全局的threadLocal
    public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String accessToken = request.getHeader("token");
            if (accessToken == null) {
                accessToken = request.getParameter("token");
            }


            if (StringUtils.isNotBlank(accessToken)) {
                Claims claims = JWTUtil.checkJWT(accessToken);
                if (claims == null) {
                    //告诉登录过期，重新登录
                    CommonUtil.sendJsonMessage(response, JsonData.buildError("登录过期，重新登录"));
                    return false;
                }
                Long id = Long.valueOf(claims.get("id").toString());
                String headImg = (String) claims.get("head_img");
                String mail = (String) claims.get("mail");
                String name = (String) claims.get("name");

                LoginUser loginUser = new LoginUser();
                loginUser.setId(id);
                loginUser.setName(headImg);
                loginUser.setHeadImg(mail);
                loginUser.setMail(name);


                //通过threadLocal传递用户信息
                threadLocal.set(loginUser );

                return true;

            }
        } catch (Exception e) {
            log.error("拦截器错误:{}", e);
        }

        CommonUtil.sendJsonMessage(response, JsonData.buildError("token不存在，重新登录"));
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
